import socket
import threading

def handle_receive(client_socket):
    while True:
        try:
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                print("服务器已断开连接。")
                break
            print(f"服务器说: {data}")
        except ConnectionResetError:
            print("服务器异常断开连接。")
            break
    client_socket.close()

def handle_send(client_socket):
    while True:
        try:
            msg = input()
            client_socket.send(msg.encode('utf-8'))
        except (ConnectionResetError, BrokenPipeError):
            print("连接已断开，无法发送消息。")
            break
    client_socket.close()

def main():
    host = '127.0.0.1'  # 服务器IP地址（本地测试）
    port = 12345

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        client_socket.connect((host, port))
        print("已连接到服务器。")
    except ConnectionRefusedError:
        print("连接被拒绝，请检查服务器是否运行。")
        return

    receive_thread = threading.Thread(target=handle_receive, args=(client_socket,))
    send_thread = threading.Thread(target=handle_send, args=(client_socket,))

    receive_thread.start()
    send_thread.start()

    receive_thread.join()
    send_thread.join()

    client_socket.close()
    print("客户端已关闭。")

if __name__ == "__main__":
    main()